package com.starinside.wp.service.impl;

import com.starinside.wp.components.MemVerificationCache;
import com.starinside.wp.domain.Children;
import com.starinside.wp.domain.Classes;
import com.starinside.wp.domain.develop.*;
import com.starinside.wp.domain.develop.PO.*;
import com.starinside.wp.foundation.constant.FeedsConstant;
import com.starinside.wp.foundation.dto.StaffDTO;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.repository.*;
import com.starinside.wp.service.DevelopReviewService;
import com.starinside.wp.service.FeedsService;
import com.starinside.wp.utils.Convert;
import com.starinside.wp.utils.DateUtil;
import com.tuo51.foudation.utils.CopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DevelopReviewServiceImpl implements DevelopReviewService {


    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    private DevelopReviewRepository developReviewRepository;

    @Autowired
    private DevelopUserRepository developUserRepository;

    @Autowired
    private DevelopUserRecordRepository developUserRecordRepository;

    @Autowired
    private DevelopReviewItemRepository developReviewItemRepository;

    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Autowired
    private FeedsService feedsService;

    @Override
    public List<DevelopReview> monthList() {
        return developReviewRepository.findAll();
    }

    @Override
    public List<DevelopReviewItem> monthItemList(String developId) {
        return developReviewItemRepository.findByDevelopIdOrderByName(developId);
    }

    @Override
    @Transactional
    public void addUserMonth(StaffDTO staff, String childrenIds, String classId, String developId, String name, String remarks, List<DevelopUserRecordPO> list) {
        String[] ids =  childrenIds.split(",");
        List<Children> childrenList = childrenRepository.findByIdIn(ids);
        if (Objects.isNull(childrenList)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "学生不存在");
        }
        Classes classes = classesRepository.getOne(classId);
        if (Objects.isNull(classes)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "班级不存在");
        }
        DevelopReview developReview = developReviewRepository.getOne(developId);
        if (Objects.isNull(developReview)){
            throw new BusinessException(ErrorCode.IS_TARGET, "核检对象不存在！");
        }
        for (int i = 0; i < childrenList.size(); i++) {

            DevelopUser developUser   = new DevelopUser();
            developUser = developUserRepository.save(developUser);
            List<DevelopUserRecord> list1 = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                DevelopUserRecord developUserRecord = new DevelopUserRecord();
                if (Objects.nonNull(list.get(j).getId())){
                    developUserRecord =  developUserRecordRepository.getOne(list.get(j).getId());
                }
                CopyUtils.copyProperties(list.get(j),developUserRecord);
                developUserRecord.setDevelopId(developId);
                developUserRecord.setChildrenId(childrenList.get(i).getId());
                developUserRecord.setDevelopUserId(developUser.getId());
                list1.add(developUserRecord);
            }
            developUserRecordRepository.saveAll(list1);

            String sql = String.format("SELECT count(id) FROM `tc_develop_review_item` where developId=  '%s' ",developId);
            List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
            int developCount = Integer.parseInt(String.valueOf(objects1.get(0)));

            String sql2 = String.format("SELECT count(id) FROM `tc_develop_user_record` where developId=  '%s' ",developId);
            sql2 += String.format("and  childrenId=  '%s' ",childrenList.get(i).getId());
            List<Object[]> objects2 = baseNativeSqlRepository.sqlArrayList(sql2);
            int developNumber = Integer.parseInt(String.valueOf(objects2.get(0)));


            developUser.setChildrenId(childrenList.get(i).getId());
            developUser.setDevelopId(developId);
            developUser.setDevelopCount(developCount);
            developUser.setDevelopNumber(developNumber);
            developUser.setRemarks(remarks);
            developUser.setClassId(classId);
            developUser.setCreatedBy(name);
            developUserRepository.save(developUser);

            feedsService.save(staff.getId(), childrenList.get(i).getId(), staff.getAreaId(), "", FeedsConstant.DEVELOP_REVIEW, developReview.getName(), "","", "", developUser.getId());
        }

    }


    @Override
    public List<Map> recordList(String childrenId, String developId) {
        DevelopReview developReview = developReviewRepository.getOne(developId);
        if (Objects.isNull(developReview)){
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        Children children = childrenRepository.getOne(childrenId);
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "对象不存在");
        }
        String sql = String.format("SELECT count(dur.id) FROM tc_develop_user_record dur LEFT JOIN tc_develop_user du on dur.id = dur.developUserId " +
                " where  dur.childrenId    = '%s'  and du.id = '%s' ",childrenId,developId);
        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> mapList = new ArrayList<>();
        int count = Integer.parseInt(String.valueOf(objects1.get(0)));
        if (0 < count){
            String sql1 = String.format("SELECT dri.id,dri.`name`,IFNULL(dur.states,0)  FROM tc_develop_review_item dri LEFT JOIN tc_develop_review dr on dr.id = dri.developId  " +
                    " LEFT JOIN tc_develop_user_record dur on dur.developItemId = dri.id " +
                    " where  dur.childrenId    = '%s' and  dr.id =  '%s'  ",childrenId,developId);
            List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql1);
            for (int i = 0; i < objects.size(); i++) {
                Map map = new HashMap();
                map.put("name", objects.get(i)[0].toString());
                map.put("states", objects.get(i)[1].toString());
                mapList.add(map);
            }
        }else {
            String sql1 = String.format("SELECT dri.id,dri.`name`,0 states  FROM tc_develop_review_item dri LEFT JOIN tc_develop_review dr on dr.id = dri.developId " +
                    " where     dr.id =  '%s'  ",developId);
            List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql1);
            for (int i = 0; i < objects.size(); i++) {
                Map map = new HashMap();
                map.put("name", objects.get(i)[0].toString());
                map.put("states", objects.get(i)[1].toString());
                mapList.add(map);
            }
        }
        return mapList;
    }

    @Override
    @Transactional
    public void addRecord(String childrenId, String developId, String developItemIds, String states) {
        Children children = childrenRepository.getOne(childrenId);
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "宝宝不存在");
        }
        DevelopUser developUser =developUserRepository.findAllByChildrenIdAndDevelopId(childrenId,developId);
        if (Objects.isNull(developUser)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "对象不存在");
        }
        //先删除记录在添加
        developUserRecordRepository.deleteAllByChildrenIdAndDevelopItemId(childrenId,developItemIds);
        String[] ids = Convert.toStrArray(developItemIds);
        String[] states1 = Convert.toStrArray(states);
        int number = 0;
        if (ids.length == states1.length){
            for (int i = 0; i <ids.length ; i++) {
                DevelopUserRecord developUserRecord = new DevelopUserRecord();
                developUserRecord.setChildrenId(childrenId);
                developUserRecord.setDevelopItemId(ids[i]);
                developUserRecord.setStates(states1[i]);
                developUserRecordRepository.save(developUserRecord);
                number++;
            }
        }
        developUser.setDevelopNumber(number);
        developUser.setAreaId(children.getAreaId());
        developUserRepository.save(developUser);
    }


    @Override
    public Page<DevelopCountPO> count(String areaId, String classId, String name, PagerQuery pagerQuery) {

        String sql = "SELECT c.id,c.`name`,cs.id as classId,cs.`name` as className,IFNULL(COUNT(du.id),0) as count,c.aid FROM  children c  " +
                "LEFT JOIN  rel_classes_children rcc on c.id = rcc.childrenId   " +
                "LEFT JOIN classes cs  on cs.id  = rcc.classesId   LEFT JOIN  tc_develop_user du on c.id = du.childrenId    where cs.areaId= '" +areaId+
                "' and c.id is not null ";
        if (Objects.nonNull(name)) {
            sql += String.format(" and c.name like concat('%s', '%s', '%s') ", "%", name, "%");
        }

        if (Objects.nonNull(classId)){
            sql += String.format("  and cs.id = '%s' ", classId);
        }

        sql += "   GROUP BY c.id    ORDER BY du.created DESC ";

        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
        sql += String.format("  limit %s, %s ", pagerQuery.getPageNum() * pagerQuery.getPageSize() ,  pagerQuery.getPageSize());

        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<DevelopCountPO> list = new ArrayList<>();
        for (int i = 0; i <objects.size() ; i++) {
            DevelopCountPO countPO = new DevelopCountPO();
            countPO.setChildrenId(objects.get(i)[0].toString());
            countPO.setChildrenName(objects.get(i)[1].toString());
            countPO.setClassesId(objects.get(i)[2].toString());
            countPO.setClassName(objects.get(i)[3].toString());
            countPO.setCount(Integer.valueOf(objects.get(i)[4].toString()));
            list.add(countPO);
        }
        return new PageImpl<>(list, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), objects1.size());
    }

    @Override
    public Page<DevelopDetailsListPO> childrenDetailsList(String childrenId, PagerQuery pagerQuery) {

        Children children = childrenRepository.getOne(childrenId);
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "宝宝不存在");
        }

        String sql = "SELECT du.childrenId,du.developId,du.createdBy,dr.`month`,du.created,du.id  FROM `tc_develop_user` du LEFT JOIN tc_develop_review dr on du.developId = dr.id" +
                "  where du.childrenId= '" +childrenId+"' ORDER BY du.created DESC ";
        List<Object[]> objects1 = baseNativeSqlRepository.sqlArrayList(sql);
        sql += String.format("  limit %s, %s ", pagerQuery.getPageNum() * pagerQuery.getPageSize() ,  pagerQuery.getPageSize());

        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<DevelopDetailsListPO> list = new ArrayList<>();
        for (int i = 0; i <objects.size() ; i++) {
            DevelopDetailsListPO detailsList = new DevelopDetailsListPO();
            detailsList.setChildrenId(objects.get(i)[0].toString());
            detailsList.setDevelopId(objects.get(i)[1].toString());
            detailsList.setCreatedBy(objects.get(i)[2].toString());
            detailsList.setMonth(Integer.parseInt(objects.get(i)[3].toString()));
            detailsList.setCreated((Date) objects.get(i)[4]);
            detailsList.setDevelopUserId(objects.get(i)[5].toString());
            double actualMonth = DateUtil.betweenMonthsV2((Date) objects.get(i)[4],children.getBirthday() );
            detailsList.setChildrenMonth((int)actualMonth);
            list.add(detailsList);
        }
        return new PageImpl<>(list, PageRequest.of(pagerQuery.getPageNum(), pagerQuery.getPageSize()), objects1.size());

    }


    @Override
    public DevelopDetailsPO childrenDetails(String developUserId) {

        DevelopUser developUser = developUserRepository.getOne(developUserId);
        if (Objects.isNull(developUser)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "记录不存在");
        }
        Children children = childrenRepository.getOne(developUser.getChildrenId());
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "宝宝不存在");
        }
        DevelopReview developReview  = developReviewRepository.getOne(developUser.getDevelopId());
        if (Objects.isNull(developReview)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "检查项不存在");
        }
        DevelopDetailsPO developDetailsPO = new DevelopDetailsPO();

        developDetailsPO.setChildren(children);
        developDetailsPO.setChildrenId(children.getId());
        developDetailsPO.setMonth(developReview.getMonth());
        double actualMonth = DateUtil.betweenMonthsV2(developUser.getCreated(), children.getBirthday());
        developDetailsPO.setChildrenMonth((int)actualMonth);
        developDetailsPO.setHeadImg(children.getImgUrl());
        developDetailsPO.setChildrenName(children.getName());
        developDetailsPO.setRemarks(developUser.getRemarks());
        developDetailsPO.setCreatedBy(developUser.getCreatedBy());
        String sql = "SELECT dri.`name`,dri.monthAge,du.states,IFNULL(dri.target,''),IFNULL(dri.details,''),dri.id  FROM `tc_develop_user_record` du INNER JOIN  tc_develop_review_item dri on du.developItemId = dri.id" +
                "  where du.developUserId= '" +developUserId+"'  ORDER BY  dri.`name` ";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);

        List<DevelopItemDetailsPO> list = new ArrayList<>();
        for (int i = 0; i <objects.size() ; i++) {
            DevelopItemDetailsPO developItemDetails = new DevelopItemDetailsPO();
            developItemDetails.setName(objects.get(i)[0].toString());
            developItemDetails.setMonthAge(Integer.valueOf(objects.get(i)[1].toString()));
            developItemDetails.setStates(Integer.valueOf(objects.get(i)[2].toString()));
            developItemDetails.setTarget(objects.get(i)[3].toString());
            developItemDetails.setDetails(objects.get(i)[4].toString());
            developItemDetails.setItemId(objects.get(i)[5].toString());
            list.add(developItemDetails);
        }
        developDetailsPO.setList(list);
        return developDetailsPO;
    }
}
